package com.invengo.device;

import android.util.Log;

import com.rfid.api.ADReaderInterface;
import com.rfid.api.GFunction;
import com.rfid.def.ApiErrDefinition;
import com.rfid.def.RfidDef;

/**
 * 这是主动扫描相关的线程
 */
public class ThreadAutoScan implements  ThreadInterface {

    private ScanCallback callback;
    private ADReaderInterface m_reader;

    public ThreadAutoScan(ADReaderInterface m_reader, ScanCallback scanCllback) {
        this.m_reader = m_reader;
        this.callback = scanCllback;
    }

    private boolean bGetScanRecordFlg = false;

    @Override
    public void run() {
        int nret;
        bGetScanRecordFlg = true;
        byte gFlg = 0x00;//
        Object dnhReport;
        while (bGetScanRecordFlg) {
            nret = m_reader.RDR_BuffMode_FetchRecords(gFlg);
            if (nret != ApiErrDefinition.NO_ERROR) {
                gFlg = 0x00;
                continue;
            }
            gFlg = 0x01;
            dnhReport = m_reader
                    .RDR_GetTagDataReport(RfidDef.RFID_SEEK_FIRST);
            while (dnhReport != null) {
                String strData;
                byte[] byData = new byte[32];
                int[] len = new int[1];
                len[0] = byData.length;
                if (ADReaderInterface.RDR_ParseTagDataReportRaw(dnhReport, byData, len) == 0) {
                    if (len[0] > 0) {
                        strData = GFunction.encodeHexStr(byData, len[0]);
                        callback.result(strData.substring(0, 16), strData.substring(16, 40));
                    }
                }
                dnhReport = m_reader.RDR_GetTagDataReport(RfidDef.RFID_SEEK_NEXT);
            }
        }
        bGetScanRecordFlg = false;

    }

    @Override
    public void setThreadRun(boolean run) {
        bGetScanRecordFlg = run;
    }

    @Override
    public boolean isThreadRun() {
        return bGetScanRecordFlg;
    }
}
